<template>
  <div class="broadcast-container">
    <div class="main-content">
      <!-- 左侧：广播类型 -->
      <div class="left-panel">
        <div class="panel-header">
          <span>广播类型</span>
          <el-button type="primary" size="small" class="setting-btn">设置</el-button>
        </div>
        <div class="type-selection">
          <div class="radio-group">
            <el-radio v-for="type in broadcastTypeList" :key="type.id" v-model="selectedType" :label="type.id">
              {{ type.broadTypeName }}
            </el-radio>
          </div>
        </div>

        <div class="bed-selection">
          <div class="bed-header">
            <span>选择床位 (必选)</span>
            <div class="bed-actions">
              <el-button size="small" @click="selectAll">全选</el-button>
              <el-button size="small" @click="inverseSelect">反选</el-button>
            </div>
          </div>

          <div class="bed-list">
            <div class="bed-buttons">
              <el-button v-for="bed in bedList" :key="bed.bedId"
                :class="{ 'selected-bed': selectedBeds.includes(bed.bedId) }" @click="toggleBedSelection(bed.bedId)"
                size="default">
                {{ bed.bedCode }} {{ bed.patientName }}
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间：广播内容 -->
      <div class="middle-panel">
        <div class="panel-header">
          <span>广播模板</span>
          <el-button type="primary" size="small" class="setting-btn">设置</el-button>
        </div>

        <div class="template-content">
          <el-checkbox v-for="template in broadCastList" :key="template.id" v-model="selectedTemplateIds"
            :label="template.id">
            {{ template.broadCastContent }}
          </el-checkbox>
        </div>

        <div class="guidance-section">
          <div class="guidance-header">宣教与指南</div>
          <div class="guidance-tree">
            <el-tree :data="guidanceTree" show-checkbox node-key="value" :props="defaultProps"
              @check="handleCheckChange" ref="guidanceTreeRef"></el-tree>
          </div>
        </div>
      </div>

      <!-- 右侧：任务名称和保存 -->
      <div class="right-panel">
        <div class="task-name">
          <span>任务名称：</span>
          <el-input v-model="displayTaskName" placeholder="请输入任务名称"></el-input>
        </div>

        <div class="save-btn">
          <el-button type="primary" @click="saveBroadcast">保存</el-button>
        </div>

        <div class="record-btn">
          <el-button link type="info" @click="viewRecords">广播记录  查看</el-button>
       
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import http from '@/api/http'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 选择的广播类型
const selectedType = ref(0) // 默认值设为0，等待数据加载后再设置

// 床位列表
const bedList = ref([])

// 选中的床位ID列表
const selectedBeds = ref([])

// 任务名称
const taskName = ref('')

// 任务名称 - 仅用于显示，不参与添加操作
const displayTaskName = ref('')

// 广播模板数据
const broadcastContentList = ref([])

// 广播类型列表
const broadcastTypeList = ref([])

// 选中的宣教与指南项目
const selectedGuidanceNodes = ref([])

// 选中的模板ID
const selectedTemplateIds = ref([])

// 选中的模板ID和内容ID数组
const selectedContentIds = ref([])

//广播管理
const broadcastManage = ref({
  taskId: 0,
  broadCastTypeId: 0,
  broadCastContent: '',
  templateName: '',
  wardAreaId: 0,
  wardId: 0,
  bedId: 0,
  patientId: 0,
  sortId: 0,
  isUse: 1,
  createTime: ''
})

// 当前类型的模板数据
const currentTypeTemplates = computed(() => {
  if (!broadcastContentList.value.length) return []
  return broadcastContentList.value.filter(item =>
    selectedType.value === 0 || item.broadcastType === selectedType.value
  )
})

// 树形控件引用
const guidanceTreeRef = ref(null)

// 改变树形控件配置，匹配后端数据格式
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 宣教与指南树结构数据
const guidanceTree = ref([])

// 获取宣教与指南数据
const getGuidanceData = async () => {
  try {
    const res = await http.get('/api/BroadController/GetBroadCastTemplateList')
    if (res) {
      guidanceTree.value = res.data
    } else {
      ElMessage.error('获取宣教与指南数据失败')
    }
  } catch (error) {
    console.error('获取宣教与指南数据失败', error)
    ElMessage.error('获取宣教与指南数据失败')
  }
}

// 处理宣教树选中变化
const handleCheckChange = (data, checked) => {
  if (checked.checkedNodes && checked.checkedNodes.length > 0) {
    selectedGuidanceNodes.value = checked.checkedNodes.map(node => ({
      value: node.value,
      name: node.name
    }))

    // 当选择宣教节点时，仅在用户未输入任务名称时自动更新模板名称
    if (selectedGuidanceNodes.value.length > 0 && !displayTaskName.value) {
      // 使用第一个选中的宣教名称作为任务名称
      displayTaskName.value = selectedGuidanceNodes.value[0].name
    }
  } else {
    selectedGuidanceNodes.value = []
  }
}

// 获取病区和床位数据
const getBedList = async () => {
  try {
    const res = await http.get('/api/DoctorManageController/GetPatients')
    if (res) {
      bedList.value = res.map(patient => ({
        bedId: patient.id, // 使用patient.id作为bedId
        bedCode: patient.bedCode || '暂无床位',
        patientId: patient.id,
        patientName: patient.name || '暂无患者',
        wardAreaCode: patient.wardAreaCode,
        wardCode: patient.wardCode,
        nursingUnitId: patient.nursingUnitId
      }))
      console.log('床位数据:', bedList.value)
    } else {
      ElMessage.error('获取床位列表失败')
    }
  } catch (error) {
    console.error('获取床位列表失败', error)
    ElMessage.error('获取床位列表失败')
  }
}

//获取广播类型
const getBroadcastType = async () => {
  const res = await http.get('/api/BroadController/GetBroadTypeList')
  if (res && res.data) {
    broadcastTypeList.value = res.data
    // 设置默认选中第一个类型
    if (broadcastTypeList.value.length > 0) {
      selectedType.value = broadcastTypeList.value[0].id
    }
  }
}

// 全选
const selectAll = () => {
  selectedBeds.value = bedList.value.map(bed => bed.bedId)
  console.log('全选床位:', selectedBeds.value)
}

// 反选
const inverseSelect = () => {
  const allBedIds = bedList.value.map(bed => bed.bedId)
  selectedBeds.value = allBedIds.filter(id => !selectedBeds.value.includes(id))
  console.log('反选床位:', selectedBeds.value)
}

// 切换床位选择状态
const toggleBedSelection = (bedId) => {
  console.log('切换床位:', bedId)
  const index = selectedBeds.value.indexOf(bedId)
  if (index === -1) {
    selectedBeds.value.push(bedId)
  } else {
    selectedBeds.value.splice(index, 1)
  }
  console.log('当前选中床位:', selectedBeds.value)
}

// 保存广播
const saveBroadcast = async () => {
  if (!selectedType.value) {
    return ElMessage.warning('请选择广播类型')
  }

  if (selectedBeds.value.length === 0) {
    return ElMessage.warning('请至少选择一个床位')
  }

  // 获取选中的模板内容ID
  const contentIds = [...selectedTemplateIds.value]

  if (contentIds.length === 0) {
    return ElMessage.warning('请选择广播内容')
  }

  // 获取宣教与指南的名称作为显示用的任务名称
  if (selectedGuidanceNodes.value.length > 0 && !displayTaskName.value) {
    // 使用宣教与指南的名称作为模板名称
    displayTaskName.value = selectedGuidanceNodes.value.map(node => node.name).join('、')
  }

  try {
    // 构建符合后端API要求的BroadCastManage对象列表
    const broadCastManageList = selectedBeds.value.map((bedId, index) => {
      // 从病人集合中找到对应的病人信息
      const bed = bedList.value.find(b => b.bedId === bedId)

      // 确保从病人集合中获取病区和病房信息
      const wardAreaId = bed && bed.wardAreaCode ? bed.wardAreaCode : ''
      const wardId = bed && bed.wardCode ? bed.wardCode : ''

      // 获取选中的宣教与指南节点的名称
      let templateName = ''
      if (selectedGuidanceNodes.value.length > 0) {
        templateName = selectedGuidanceNodes.value[0].name // 使用第一个选中节点的名称
      }

      // 构建完全符合后端API期望的对象
      const item = {
        id: 0,
        taskId: 1,
        broadCastTypeId: selectedType.value,
        broadCastContent: contentIds.join(','),
        templateName: templateName,
        wardAreaId: wardAreaId,
        wardId: wardId,
        bedId: bedId,
        patientId: bed ? bed.patientId : 0,
        sortId: 1,
        isUse: 1,
        createTime: new Date().toISOString()
      }

      // 对字段做一些调整，尝试匹配后端期望的字段
      // 注意：后端可能期望的是驼峰命名法或首字母大写的命名法
      return {
        id: 0,
        taskId: 1,
        broadCastTypeId: selectedType.value,
        broadCastContent: contentIds.join(','),
        templateName: templateName,
        wardAreaId: wardAreaId,
        wardId: wardId,
        bedId: bedId,
        patientId: bed ? bed.patientId : 0,
        sortId: 1,
        isUse: 1,
        createTime: new Date().toISOString()
      }
    })

    // 完整打印请求数据便于调试


    console.log('发送的数据详情:', broadCastManageList)
    const res = await http.post('/api/BroadController/AddBroadCastManageList', broadCastManageList, true)

    if (res && res.status) {
      ElMessage.success('添加成功')
      // 重置表单
      resetForm()
      router.push('/BroadCastManageList')
    } else {
      // 尝试方式2: 包装成对象
      console.log('尝试方式2: 包装成对象')
      const wrappedData = { broadCastManageList: broadCastManageList }
      console.log('包装后的数据:', wrappedData)

      const res2 = await http.post('/api/BroadController/AddBroadCastManageList', wrappedData, true)

      if (res2 && res2.status) {
        ElMessage.success('添加成功')
        router.push('/BroadCastManageList')
        // 重置表单
        resetForm()
      } else {
        ElMessage.error(res2 ? res2.message : res.message || '添加失败')
      }
    }
  } catch (error) {
    console.error('添加失败', error)
    console.error('错误详情:', error.response || error.message || error)
    ElMessage.error('添加失败: ' + (error.message || '未知错误'))
  }
}

// 重置表单
const resetForm = () => {
  selectedBeds.value = []
  taskName.value = ''
  displayTaskName.value = ''
  selectedTemplateIds.value = []
  selectedGuidanceNodes.value = []
  selectedContentIds.value = []
  if (guidanceTreeRef.value) {
    guidanceTreeRef.value.setCheckedKeys([])
  }
  broadcastManage.value = {
    taskId: 1, // 默认设置为1
    broadCastTypeId: selectedType.value,
    broadCastContent: '',
    templateName: '', // 重置模板名称
    wardAreaId: '',
    wardId: '',
    bedId: 0,
    patientId: 0,
    sortId: 0,
    isUse: 1,
    createTime: ''
  }
}

// 查看广播记录
const viewRecords = () => {
  // 跳转到广播记录页面
  window.location.href = '#/BroadLog';
}

// 查看详情
const viewDetails = () => {
  // TODO: 查看详情
}

// 模板列表 (改为computed，用于兼容旧代码)
const broadCastList = ref([])

//获取广播模板
const getBroadCastList = async () => {
  const res = await http.get('/api/BroadController/GetBroadList')
  if (res && res.status) {
    broadCastList.value = res.data
  }
}

// 监听选择类型变化
watch(selectedType, (newVal) => {
  broadcastManage.value.broadCastTypeId = newVal
  // 清空已选模板
  selectedTemplateIds.value = []
  selectedContentIds.value = []
})

// 监听选中的内容变化
watch([selectedTemplateIds, selectedGuidanceNodes], ([newTemplateIds, newGuidanceNodes]) => {
  // 直接使用ID数组
  broadcastManage.value.broadCastContent = newTemplateIds.join(',')
}, { deep: true })

// 监听任务名称变化
watch(taskName, (newVal) => {
  broadcastManage.value.templateName = newVal
})

// 监听床位选择变化
watch(selectedBeds, (newVal) => {
  if (newVal.length === 1) {
    const bed = bedList.value.find(b => b.bedId === newVal[0])
    if (bed) {
      broadcastManage.value.bedId = bed.bedId
      broadcastManage.value.patientId = bed.patientId
      broadcastManage.value.wardAreaId = bed.wardAreaCode
      broadcastManage.value.wardId = bed.wardCode
    }
  }
})

// 切换模板选中状态
const toggleTemplateSelection = (templateId) => {
  const index = selectedTemplateIds.value.indexOf(templateId)
  if (index === -1) {
    selectedTemplateIds.value.push(templateId)
  } else {
    selectedTemplateIds.value.splice(index, 1)
  }
}

// 获取选中的模板内容
const getSelectedTemplateContent = () => {
  const selectedTemplates = broadcastContentList.value.filter(
    template => selectedTemplateIds.value.includes(template.id)
  )
  return selectedTemplates.map(t => t.broadcastContent).join('\n')
}

onMounted(() => {
  getBedList()
  getGuidanceData()
  getBroadcastType()
  getBroadCastList()
})
</script>

<style scoped>
.broadcast-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.main-content {
  display: flex;
  gap: 20px;
}

.left-panel,
.middle-panel,
.right-panel {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.left-panel {
  flex: 1;
  min-width: 300px;
}

.middle-panel {
  flex: 1.5;
  min-width: 350px;
}

.right-panel {
  flex: 0.8;
  min-width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 15px;
  font-weight: bold;
}

.setting-btn {
  font-size: 12px;
  padding: 4px 8px;
}

.radio-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  margin-bottom: 20px;
}

.bed-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-weight: bold;
}

.bed-actions {
  display: flex;
  gap: 5px;
}

.bed-list {
  border: 1px solid #eee;
  padding: 10px;
  height: 400px;
  overflow-y: auto;
}

.bed-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.bed-buttons .el-button {
  margin: 0;
  min-width: 120px;
  text-align: center;
  height: 36px;
  line-height: 1.2;
  font-size: 13px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  color: #606266;
}

.selected-bed {
  background-color: #409EFF !important;
  color: white !important;
  border-color: #409EFF !important;
}

.template-content {
  border: 1px solid #eee;
  padding: 10px;
  margin-bottom: 20px;
  max-height: 150px;
  overflow-y: auto;
}

.template-content .el-checkbox {
  display: block;
  margin-bottom: 10px;
}

.guidance-header {
  font-weight: bold;
  margin-bottom: 10px;
}

.guidance-tree {
  border: 1px solid #eee;
  padding: 10px;
  height: 250px;
  overflow-y: auto;
}

.task-name {
  margin-bottom: 30px;
  display: flex;
  align-items: center;
}

.task-name span {
  white-space: nowrap;
  margin-right: 5px;
}

.save-btn {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 30px;
}

.save-btn .el-button {
  width: 80%;
}

.record-btn {
  margin-top: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 40px;
}
</style>
